package com.system.vote.admin.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.system.vote.admin.entity.TWxUserinfo;
import com.system.vote.admin.service.TWxUserinfoService;
import com.system.vote.common.utils.StringUtils;
import com.system.vote.core.customBean.PageBean;
import com.system.vote.core.http.Result;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@Api(tags = "PC后台投票用户管理")
@RequestMapping("/vote/userInfo")
public class VoteUserInfoController {
    @Autowired
    BCryptPasswordEncoder bCryptPasswordEncoder;

    @Value("${originPwd}")
    private String originPwd;

    @Autowired
    private TWxUserinfoService tWxUserinfoService;

    @PostMapping("/list")
    @PreAuthorize("hasAuthority('vote:userInfo:list')")
    public Result list(@RequestBody PageBean pageBean) {
        String query = pageBean.getQuery().trim();
        Page<TWxUserinfo> pageResult = tWxUserinfoService.page(
                new Page<>(pageBean.getPageNum(),
                        pageBean.getPageSize()),
                new QueryWrapper<TWxUserinfo>()
                        .like(StringUtils.isNotEmpty(query), "nick_name", query)
                        .orderByDesc("last_login_date"));
        List<TWxUserinfo> listData = pageResult.getRecords();

        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("list", listData);
        resultMap.put("total", pageResult.getTotal());
        return Result.success(resultMap);
    }

    @PostMapping("/updateUserStatus")
    @PreAuthorize("hasAuthority('vote:userInfo:edit')")
    public Result updateUserStatus(@RequestBody TWxUserinfo tWxUserinfo) {
        TWxUserinfo currentTWxUserinfo = tWxUserinfoService.getById(tWxUserinfo.getId());
        currentTWxUserinfo.setStatus(tWxUserinfo.getStatus());
        tWxUserinfoService.updateById(currentTWxUserinfo);
        String msg = "";
        if (Objects.equals(tWxUserinfo.getStatus(), "0")) {
            msg = "启用用户成功";
        } else {
            msg = "禁用用户成功";
        }
        return Result.success(msg);
    }
    @GetMapping("/resetPwd/{id}")
    @PreAuthorize("hasAuthority('vote:userInfo:edit')")
    public Result resetPwd(@PathVariable Long id) {
        TWxUserinfo tWxUserinfo = tWxUserinfoService.getById(id);
        tWxUserinfo.setPassword(bCryptPasswordEncoder.encode(originPwd));
        tWxUserinfoService.updateById(tWxUserinfo);
        return Result.success("重置密码成功");
    }
}
